package com.yuhuihui.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * xml工具类--以jackson操作
 *
 * @author yuhh
 * @date 2023-05-25 14:50:02
 */
public final class XmlJacksonUtil {

    /** logger */
    private static final Logger logger = LoggerFactory.getLogger(XmlJacksonUtil.class);

    private final static XmlMapper XML_MAPPER = XmlMapper.xmlBuilder().enable(MapperFeature.USE_STD_BEAN_NAMING).build();

    static {
        /* 字段为null，自动忽略，不再序列化 */
        XML_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * object转xml
     *
     * @param object 需要转换的对象
     * @return {@link String } 转化后的xml
     * @author yuhh
     * @date 2023-05-25 14:50:08
     */
    public static <T> String objectToXml(T object) {
        try {
            return XML_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
           logger.error("{}转换成xml出现异常", object.toString(), e);
        }
        return null;
    }

    /**
     * xml转对象
     *
     * @param xml   需要转换的xml
     * @param clazz 需要转换成的对象
     * @return {@link T } 转换后的对象
     * @author yuhh
     * @date 2023-05-25 14:50:13
     */
    public static <T> T xmlToObject(String xml,Class<T> clazz) {
        try {
            return XML_MAPPER.readValue(xml, clazz);
        } catch (JsonProcessingException e) {
            logger.error("{}转换为对象出现异常", xml, e);
        }
        return null;
    }

    private XmlJacksonUtil(){}
}
